package com.xes.rabbitmq.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.xes.rabbitmq.core.constant.MessageConstant;
import com.xes.rabbitmq.core.domain.tables.daos.TbMessageDao;
import com.xes.rabbitmq.core.domain.tables.daos.TbStudentDao;
import com.xes.rabbitmq.core.domain.tables.pojos.TbMessage;
import com.xes.rabbitmq.core.domain.tables.pojos.TbStudent;
import com.xes.rabbitmq.core.enums.MessageStatusEunm;
import com.xes.rabbitmq.core.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private TbStudentDao studentDao;

    @Autowired
    private TbMessageDao messageDao;

    @Transactional
    @Override
    public void createStudent(TbStudent student, String messageId) {
        studentDao.insert(student);

        TbMessage message = new TbMessage();
        LocalDateTime now = LocalDateTime.now();
        message.setId(messageId);
        message.setCreateTime(now);
        message.setMessage(JSON.toJSONString(student));
        message.setOperateTime(now);
        message.setNextRetryTime(now.plusSeconds(MessageConstant.NEXT_TIMEOUT));
        message.setRetryTimes(0);
        message.setStatus(MessageStatusEunm.SENDING.getValue());
        messageDao.insert(message);
    }
}
